package sy.service.base.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import sy.dao.base.BaseDaoI;
import sy.service.base.BaseServiceI;
import sy.util.base.QueryFilter;

@Service("baseService")
public class BaseServiceImpl<T extends Serializable, PK extends Serializable> implements BaseServiceI<T, PK> {

	@Resource(name = "baseDao")
	private BaseDaoI<T, PK> baseDao;

	@Override
	public T get(PK pk) {
		return this.baseDao.get((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0], pk);
	}

	@Override
	public T save(T o) {
		return this.baseDao.save(o);
	}

	@Override
	public T update(T o) {
		return this.baseDao.update(o);
	}

	@Override
	public T saveOrUpdate(T o) {
		return this.baseDao.saveOrUpdate(o);
	}

	@Override
	public void delete(T o) {
		this.baseDao.delete(o);
	}

	@Override
	public T find(QueryFilter filter) {
		String className = ((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]).getName();
		String hql = " select distinct t from " + className + " t where 1=1 ";
		return this.baseDao.find(hql + filter.getWhere() + filter.getSortAndOrder(), filter.getParams());
	}

	@Override
	public List<T> findAll(QueryFilter filter) {
		String className = ((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]).getName();
		String hql = " select count(distinct t) from " + className + " t where 1=1 ";
		filter.setTotal(this.baseDao.total(hql + filter.getWhere(), filter.getParams()));
		hql = " select distinct t from " + className + " t where 1=1 ";
		return this.baseDao.findAll(hql + filter.getWhere() + filter.getSortAndOrder(), filter.getParams(), filter.getPage(), filter.getRows());
	}

	@Override
	public List<T> findAll() {
		QueryFilter filter = new QueryFilter();
		return this.findAll(filter);
	}

}
